package com.novatec.util;

import javax.sql.DataSource;

//import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class Sesion {
	//transient private Logger log = Logger.getLogger(Sesion.class);
	transient private SimpleJdbcTemplate simpleJdbcTemplate;
	private long idUsuario = -1;

	@Autowired
    public void init(DataSource dataSource) {
        this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
    }

	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public long getIdUsuario() {
		if (idUsuario == -1) {
			String login;
			Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

			if (principal instanceof UserDetails) {
				login = ((UserDetails) principal).getUsername();
			} else {
				login = principal.toString();
			}

			idUsuario = simpleJdbcTemplate.queryForLong("SELECT idusuario FROM usuario WHERE login = ?", login);
		}

		return idUsuario;
	}
/*	
	@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
	public long getRUC_DNI() {
		if (rucdni == -1) {
			String login;
			Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

			if (principal instanceof UserDetails) {
				login = ((UserDetails) principal).getUsername();
			} else {
				login = principal.toString();
			}

			rucdni = simpleJdbcTemplate.queryForLong("select c.RUC_DNI from cliente c inner join usuario u on u.Idusuario=c.Idusuario where u.Login=?", login);

			log.debug(rucdni);
		}

		return rucdni;
	}
*/
}
